package com.google.code.avajhelpdesk.pages.auth;

import org.apache.wicket.Application;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.value.ValueMap;
import org.apache.wicket.validation.validator.StringValidator;

import com.google.code.avajhelpdesk.MyWebSession;
import com.google.code.avajhelpdesk.entities.User;
import com.google.code.avajhelpdesk.pages.BasePage;


public class SignInPage extends BasePage {

	private static class LoginForm extends Form {
		
		private static final long serialVersionUID = 1L;
		private static final String PASSWORD_KEY = "password";
		private static final String LOGIN_KEY = "login";
		
		private ValueMap properties = new ValueMap();
		
		@SuppressWarnings("unchecked")
		public LoginForm(String id) {
			super(id);
			add(new TextField(LOGIN_KEY, 
					new PropertyModel(properties, LOGIN_KEY))
							.setRequired(true)
							.add(StringValidator.maximumLength(User.MAX_USERNAME_LENGTH)));
			
			add(new PasswordTextField(PASSWORD_KEY, 
					new PropertyModel(properties, PASSWORD_KEY))
							.add(StringValidator.maximumLength(User.MAX_PASSWORD_LENGTH)));
		}
		
		@Override
		protected void onSubmit() {
			MyWebSession session = (MyWebSession) getSession();
			
			String login = properties.getString(LOGIN_KEY);
			String password = properties.getString(PASSWORD_KEY);
			
			if (session.signIn(login, password)) {
				if (!continueToOriginalDestination()) {
					setResponsePage(getApplication().getSessionSettings().getPageFactory().newPage(
							Application.get().getHomePage()));
				}
				
			} else {
				error("Authentication error: specified login and password mismatch");
			}
		}
	}
	
	public SignInPage() {
		super();
		FeedbackPanel feedback = new FeedbackPanel("login-form-feedback");
		add(feedback);
		
		add(new LoginForm("login-form"));
	}

	@Override
	protected String getPageTitle() {
		return "Login";
	}
}
